<template>
  <div class="route-map">
    <div 
      id="map" 
      ref="mapRef"
      class="map-container"
    ></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import 'leaflet/dist/leaflet.css'
import L from 'leaflet'
import { addressService } from '@/services/addressService'

const props = defineProps({
  routePoints: {
    type: Array,
    default: () => []
  },
  currentLocation: {
    type: Object,
    default: null
  },
  shipmentInfo: {
    type: Object,
    default: () => ({})
  }
})

const mapRef = ref(null)
const map = ref(null)
const mapInitialized = ref(false)
const isDestroyed = ref(false)

// 格式化时间
const formatTimestamp = (timestamp) => {
  if (!timestamp) return '-'
  if (typeof timestamp === 'number') {
    return new Date(timestamp).toLocaleString()
  }
  return new Date(timestamp).toLocaleString()
}

// 简化的安全检查地图状态
const isMapValid = () => {
  return !isDestroyed.value && 
         map.value && 
         map.value._container && 
         mapInitialized.value
}

// 简化的安全执行地图操作
const safeMapOperation = (operation, fallback = null) => {
  try {
    if (!isMapValid()) {
      return fallback
    }
    return operation()
  } catch (error) {
    console.warn('地图操作失败:', error)
    return fallback
  }
}

// 初始化地图 - 简化配置，移除过度的错误处理
const initMap = () => {
  if (map.value || mapInitialized.value || isDestroyed.value) return
  
  try {
    if (!mapRef.value) {
      console.error('地图容器元素不存在')
      return
    }
    
    // 使用默认配置，只禁用关键的动画
    map.value = L.map(mapRef.value, {
      zoomControl: true,
      attributionControl: true,
      preferCanvas: false, // 改回默认值
      fadeAnimation: false,
      zoomAnimation: false, // 禁用缩放动画防止错误
      markerZoomAnimation: false,
      trackResize: false, // 保持这个关键设置
      zoomSnap: 1,
      zoomDelta: 1
    }).setView([31.2304, 121.4737], 12)
    
    // 添加底图
    const tileLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
      maxZoom: 18,
      minZoom: 3,
      subdomains: ['a', 'b', 'c']
    })
    tileLayer.addTo(map.value)
    
    // 简化的事件处理 - 移除过度的状态重置
    map.value.on('popupclose', () => {
      console.log('弹窗关闭')
      // 简单的清理，不触发重新渲染
      setTimeout(() => {
        safeMapOperation(() => {
          if (map.value.scrollWheelZoom) {
            map.value.scrollWheelZoom.enable()
          }
        })
      }, 100)
    })
    
    // 监听地图准备就绪
    map.value.whenReady(() => {
      if (isDestroyed.value) return
      
      mapInitialized.value = true
      console.log('地图初始化完成')
      
      nextTick(() => {
        safeMapOperation(() => {
          map.value.invalidateSize(false)
        })
      })
    })
    
  } catch (error) {
    console.error('初始化地图失败:', error)
    mapInitialized.value = false
  }
}

// 简化的路线渲染
const renderRoute = async () => {
  if (!isMapValid() || props.routePoints.length === 0) {
    return
  }
  
  try {
    // 清除现有图层（除了底图和当前位置标记）
    const layersToRemove = []
    map.value.eachLayer(layer => {
      if (!(layer instanceof L.TileLayer) && !layer.options?.isCurrentLocation) {
        layersToRemove.push(layer)
      }
    })
    
    layersToRemove.forEach(layer => {
      try {
        if (map.value.hasLayer(layer)) {
          map.value.removeLayer(layer)
        }
      } catch (error) {
        console.warn('移除图层失败:', error)
      }
    })
    
    // 创建路线点
    const points = props.routePoints.map(point => [point.lat, point.lng])
    const validPoints = points.filter(point => 
      point.length === 2 && 
      !isNaN(point[0]) && 
      !isNaN(point[1]) &&
      point[0] !== 0 && 
      point[1] !== 0
    )
    
    if (validPoints.length === 0) {
      console.warn('没有有效的轨迹点数据')
      return
    }
    
    console.log(`开始渲染 ${validPoints.length} 个轨迹点`)
    
    // 添加路线
    const polyline = L.polyline(validPoints, { 
      color: 'blue', 
      weight: 3,
      opacity: 0.8
    }).addTo(map.value)
    
    // 添加轨迹点标记（显示部分关键点，避免过多标记影响性能）
    const maxMarkersToShow = 10 // 最多显示10个中间轨迹点
    const step = Math.max(1, Math.floor(props.routePoints.length / maxMarkersToShow))
    
    // 筛选需要显示的轨迹点
    const pointsToShow = []
    props.routePoints.forEach((point, index) => {
      const isStartPoint = index === 0
      const isEndPoint = index === props.routePoints.length - 1
      const isIntermediatePoint = index % step === 0 && !isStartPoint && !isEndPoint
      
      if (isStartPoint || isEndPoint || (isIntermediatePoint && index < props.routePoints.length - 1)) {
        if (point.lat && point.lng && !isNaN(point.lat) && !isNaN(point.lng)) {
          pointsToShow.push({
            ...point,
            originalIndex: index,
            isStartPoint,
            isEndPoint
          })
        }
      }
    })
    
    // 批量获取地址信息
    const coordinates = pointsToShow.map(point => ({
      lat: point.lat,
      lng: point.lng
    }))
    
    console.log('开始批量获取地址信息...', coordinates.length, '个坐标点')
    const addressResults = await addressService.batchGetAddresses(coordinates)
    console.log('地址信息获取完成:', addressResults)
    
    // 创建标记点
    pointsToShow.forEach((point, index) => {
      let markerColor = '#1890ff' // 默认蓝色
      let markerTitle = '轨迹点'
      
      if (point.isStartPoint) {
        markerColor = '#52c41a' // 绿色起点
        markerTitle = '起点'
      } else if (point.isEndPoint) {
        markerColor = '#f5222d' // 红色终点  
        markerTitle = '终点'
      }
      
      const trackMarker = L.marker([point.lat, point.lng], {
        icon: L.divIcon({
          className: 'track-point-marker',
          html: `<div style="background-color: ${markerColor}; width: 8px; height: 8px; border-radius: 50%; border: 2px solid white; box-shadow: 0 0 4px rgba(0,0,0,0.3);"></div>`,
          iconSize: [12, 12],
          iconAnchor: [6, 6]
        })
      }).addTo(map.value)
      
      // 获取对应的地址信息
      const addressResult = addressResults[index]
      const address = addressResult ? addressService.formatAddress(addressResult) : '地址获取中...'
      
      // 创建详细的弹窗内容
      const popupContent = `
        <div style="min-width: 240px;">
          <h4 style="margin: 0 0 10px 0; color: ${markerColor};">📍 ${markerTitle}</h4>
          <p><strong>时间:</strong> ${point.time || formatTimestamp(point.timestamp)}</p>
          <p><strong>坐标:</strong> [${point.lat}, ${point.lng}]</p>
          <p><strong>地址:</strong> <span style="color: #666; font-size: 12px;">${address}</span></p>
          <p><strong>速度:</strong> ${point.speed || 0} km/h</p>
          ${point.altitude !== undefined ? `<p><strong>海拔:</strong> ${point.altitude} m</p>` : ''}
          ${point.mileage !== undefined ? `<p><strong>里程:</strong> ${point.mileage} km</p>` : ''}
          ${point.isStartPoint ? `<p><strong>取货仓库:</strong> ${props.shipmentInfo.pickup_warehouse || '-'}</p>` : ''}
          ${point.isEndPoint ? `<p><strong>卸货仓库:</strong> ${props.shipmentInfo.delivery_warehouse || '-'}</p>` : ''}
        </div>
      `
      
      trackMarker.bindPopup(popupContent, {
        closeOnClick: true,
        autoPan: false,
        animate: false
      })
    })
    
    // 添加起点标记
    if (validPoints.length > 0) {
      // 获取起点的地址信息
      const startPointData = pointsToShow.find(p => p.isStartPoint)
      const startAddressResult = startPointData ? addressResults[pointsToShow.indexOf(startPointData)] : null
      const startAddress = startAddressResult ? addressService.formatAddress(startAddressResult) : '地址获取中...'
      
      const startMarker = L.marker(validPoints[0], {
        icon: L.divIcon({
          className: 'start-point-marker',
          html: '<div style="background-color: green; width: 12px; height: 12px; border-radius: 50%; border: 2px solid white;"></div>',
          iconSize: [16, 16],
          iconAnchor: [8, 8]
        })
      }).addTo(map.value)
      
      startMarker.bindPopup(`
        <div>
          <h4>起点</h4>
          <p><strong>地址:</strong> <span style="color: #666; font-size: 12px;">${startAddress}</span></p>
          <p><strong>取货仓库:</strong> ${props.shipmentInfo.pickup_warehouse || '-'}</p>
        </div>
      `)
    }
    
    // 添加终点标记
    if (validPoints.length > 1) {
      // 获取终点的地址信息
      const endPointData = pointsToShow.find(p => p.isEndPoint)
      const endAddressResult = endPointData ? addressResults[pointsToShow.indexOf(endPointData)] : null
      const endAddress = endAddressResult ? addressService.formatAddress(endAddressResult) : '地址获取中...'
      
      const endMarker = L.marker(validPoints[validPoints.length - 1], {
        icon: L.divIcon({
          className: 'end-point-marker',
          html: '<div style="background-color: red; width: 12px; height: 12px; border-radius: 50%; border: 2px solid white;"></div>',
          iconSize: [16, 16],
          iconAnchor: [8, 8]
        })
      }).addTo(map.value)
      
      endMarker.bindPopup(`
        <div>
          <h4>终点</h4>
          <p><strong>地址:</strong> <span style="color: #666; font-size: 12px;">${endAddress}</span></p>
          <p><strong>卸货仓库:</strong> ${props.shipmentInfo.delivery_warehouse || '-'}</p>
        </div>
      `)
    }
    
    // 调整视图以适应路线 - 不使用动画
    setTimeout(() => {
      safeMapOperation(() => {
        if (polyline && map.value.hasLayer(polyline)) {
          const bounds = polyline.getBounds()
          if (bounds.isValid()) {
            map.value.fitBounds(bounds, { 
              padding: [30, 30],
              animate: false // 不使用动画
            })
          }
        }
      })
    }, 100)
    
  } catch (error) {
    console.error('渲染路线失败:', error)
  }
}

// 简化的显示当前位置
const showCurrentLocation = async () => {
  if (!isMapValid() || !props.currentLocation) {
    return
  }
  
  const { lat, lng } = props.currentLocation
  
  if (!lat || !lng || isNaN(lat) || isNaN(lng)) {
    console.warn('无效的坐标数据:', { lat, lng })
    return
  }
  
  try {
    // 清除之前的当前位置标记
    const layersToRemove = []
    map.value.eachLayer(layer => {
      if (layer.options && layer.options.isCurrentLocation) {
        layersToRemove.push(layer)
      }
    })
    
    layersToRemove.forEach(layer => {
      try {
        if (map.value.hasLayer(layer)) {
          if (layer.off) layer.off()
          map.value.removeLayer(layer)
        }
      } catch (error) {
        console.warn('移除当前位置图层失败:', error)
      }
    })
    
    // 创建当前位置标记
    const currentIcon = L.divIcon({
      className: 'current-location-marker',
      html: `
        <div style="
          background-color: #ff4444; 
          width: 16px; 
          height: 16px; 
          border-radius: 50%; 
          border: 3px solid white; 
          box-shadow: 0 0 10px rgba(255, 68, 68, 0.6);
          animation: pulse 2s infinite;
        "></div>
      `,
      iconSize: [22, 22],
      iconAnchor: [11, 11]
    })
    
    const currentMarker = L.marker([lat, lng], { 
      icon: currentIcon,
      isCurrentLocation: true
    })
    
    // 简化的弹窗事件处理
    currentMarker.on('popupopen', () => {
      safeMapOperation(() => {
        if (map.value.scrollWheelZoom) {
          map.value.scrollWheelZoom.disable()
        }
      })
    })
    
    currentMarker.on('popupclose', () => {
      setTimeout(() => {
        safeMapOperation(() => {
          if (map.value.scrollWheelZoom) {
            map.value.scrollWheelZoom.enable()
          }
        })
      }, 50)
    })
    
    currentMarker.addTo(map.value)
    
    // 直接使用后端返回的地址信息，无需再次请求
    const address = props.currentLocation.address || '地址未知'
    console.log('使用后端返回的地址信息:', address)
    
    // 创建弹窗内容
    const popupContent = `
      <div style="min-width: 240px;">
        <h4 style="margin: 0 0 10px 0; color: #ff4444;">📍 当前位置</h4>
        <p><strong>设备:</strong> ${props.currentLocation.device_name || '-'}</p>
        <p><strong>编号:</strong> ${props.currentLocation.device_id || '-'}</p>
        <p><strong>坐标:</strong> [${lng}, ${lat}]</p>
        <p><strong>地址:</strong> <span style="color: #666; font-size: 12px;">${address}</span></p>
        <p><strong>速度:</strong> ${props.currentLocation.speed || 0} km/h</p>
        <p><strong>定位时间:</strong> ${formatTimestamp(props.currentLocation.device_time)}</p>
        ${props.currentLocation.address_success === false ? `<p><em style="color: #999; font-size: 11px;">地址解析状态: ${props.currentLocation.address_success ? '成功' : '失败'}</em></p>` : ''}
      </div>
    `
    
    currentMarker.bindPopup(popupContent, {
      closeOnClick: true,
      autoPan: false,
      animate: false
    })
    
    // 移动到位置 - 不使用动画
    setTimeout(() => {
      safeMapOperation(() => {
        const currentZoom = map.value.getZoom()
        const targetZoom = Math.max(currentZoom, 14)
        
        map.value.setView([lat, lng], targetZoom, { animate: false })
        
        // 打开弹窗
        setTimeout(() => {
          if (map.value.hasLayer(currentMarker)) {
            currentMarker.openPopup()
          }
        }, 100)
      })
    }, 100)
    
  } catch (error) {
    console.error('显示当前位置失败:', error)
  }
}

// 简化的监听器 - 移除深度监听防止频繁触发
watch(() => props.routePoints, async (newPoints) => {
  if (isMapValid() && newPoints && newPoints.length > 0) {
    await renderRoute()
  }
}, { immediate: false })

watch(() => props.currentLocation, async (newLocation) => {
  if (isMapValid() && newLocation) {
    await showCurrentLocation()
  }
}, { immediate: false })

// 暴露方法给父组件
defineExpose({
  renderRoute,
  showCurrentLocation,
  invalidateSize: () => {
    safeMapOperation(() => {
      map.value.invalidateSize(false)
    })
  }
})

onMounted(() => {
  isDestroyed.value = false
  setTimeout(() => {
    if (!isDestroyed.value) {
      initMap()
    }
  }, 100)
})

onUnmounted(() => {
  isDestroyed.value = true
  
  if (map.value) {
    try {
      map.value.off()
      map.value.eachLayer(layer => {
        try {
          if (layer.off) layer.off()
          map.value.removeLayer(layer)
        } catch (error) {
          console.warn('清理图层失败:', error)
        }
      })
      map.value.remove()
    } catch (error) {
      console.warn('清理地图失败:', error)
    } finally {
      map.value = null
      mapInitialized.value = false
    }
  }
})
</script>

<style lang="scss" scoped>
.route-map {
  position: relative;
  z-index: 1;
  height: 100%;
  width: 100%;
}

.map-container {
  height: 100%;
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  z-index: 1;
  border: 1px solid #e4e7ed;
}

#map {
  height: 100%;
  width: 100%;
  position: relative;
  z-index: 1;
}

/* Leaflet地图控件的z-index调整 */
:global(.leaflet-control-container) {
  z-index: 5 !important;
}

:global(.leaflet-popup) {
  z-index: 6 !important;
}

:global(.leaflet-tooltip) {
  z-index: 6 !important;
}

/* 确保地图pane不会超出容器 */
:global(.leaflet-map-pane) {
  z-index: 1 !important;
}

:global(.leaflet-tile-pane) {
  z-index: 1 !important;
}

:global(.leaflet-overlay-pane) {
  z-index: 2 !important;
}

:global(.leaflet-shadow-pane) {
  z-index: 3 !important;
}

:global(.leaflet-marker-pane) {
  z-index: 4 !important;
}

/* 当前位置标记动画 */
:global(.current-location-marker) {
  z-index: 5 !important;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.7;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}
</style>